<template>
  <div class="version-progress">
    <el-progress
      :percentage="progressPercentage"
      :status="progressStatus"
      :stroke-width="8"
      :show-text="showText"
      :format="formatProgress"
      :class="['progress-bar', `status-${version.status}`]"
    />
    <div v-if="showDetails" class="progress-details">
      <div class="detail-item">
        <span class="label">任务:</span>
        <span class="value">{{ completedTasks }}/{{ totalTasks }}</span>
        <span class="percentage" v-if="totalTasks > 0">
          ({{ Math.round((completedTasks / totalTasks) * 100) }}%)
        </span>
      </div>
      <div class="detail-item">
        <span class="label">缺陷:</span>
        <span class="value">{{ resolvedDefects }}/{{ totalDefects }}</span>
        <span class="percentage" v-if="totalDefects > 0">
          ({{ Math.round((resolvedDefects / totalDefects) * 100) }}%)
        </span>
      </div>
      <div class="detail-item">
        <span class="label">需求:</span>
        <span class="value">{{ completedRequirements }}/{{ totalRequirements }}</span>
        <span class="percentage" v-if="totalRequirements > 0">
          ({{ Math.round((completedRequirements / totalRequirements) * 100) }}%)
        </span>
      </div>
      <div class="detail-item">
        <span class="label">测试用例:</span>
        <span class="value">{{ passedTestCases }}/{{ totalTestCases }}</span>
        <span class="percentage" v-if="totalTestCases > 0">
          ({{ Math.round((passedTestCases / totalTestCases) * 100) }}%)
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { Version } from '@/api/version'
import { useVersionStates } from '@/composables/useVersionStates'

// 从状态管理系统动态获取状态信息
const { getStateByCode } = useVersionStates()

interface VersionStats {
  total_tasks?: number
  completed_tasks?: number
  total_defects?: number
  resolved_defects?: number
  total_requirements?: number
  completed_requirements?: number
  total_test_cases?: number
  passed_test_cases?: number
}

interface Props {
  version: Version
  showText?: boolean
  showDetails?: boolean
  size?: 'small' | 'default' | 'large'
  versionStats?: VersionStats
}

const props = withDefaults(defineProps<Props>(), {
  showText: true,
  showDetails: false,
  size: 'default',
  versionStats: () => ({})
})

// 计算属性
const totalTasks = computed(() => {
  return props.versionStats?.total_tasks || (props.version as any).task_count || 0
})

const completedTasks = computed(() => {
  return props.versionStats?.completed_tasks || (props.version as any).completed_task_count || 0
})

const totalDefects = computed(() => {
  return props.versionStats?.total_defects || (props.version as any).defect_count || 0
})

const resolvedDefects = computed(() => {
  return props.versionStats?.resolved_defects || 0
})

const totalRequirements = computed(() => {
  return props.versionStats?.total_requirements || 0
})

const completedRequirements = computed(() => {
  return props.versionStats?.completed_requirements || 0
})

const totalTestCases = computed(() => {
  return props.versionStats?.total_test_cases || 0
})

const passedTestCases = computed(() => {
  return props.versionStats?.passed_test_cases || 0
})

// 计算综合进度（基于任务、缺陷、需求、测试用例的加权平均）
const progressPercentage = computed(() => {
  const totalItems = totalTasks.value + totalDefects.value + totalRequirements.value + totalTestCases.value
  
  if (totalItems === 0) {
    // 根据版本状态返回默认进度 - 从状态管理系统动态判断
    const state = getStateByCode(props.version.status)
    if (state?.name) {
      const statusName = state.name.toLowerCase()
      // 判断是否已完成状态（包含"已发布"、"已归档"、"已完成"等关键词）
      if (statusName.includes('已发布') || statusName.includes('已归档') || statusName.includes('已完成') || statusName.includes('已废弃')) {
        return 100
      }
      // 判断是否预发布状态（包含"预发布"、"发布就绪"等关键词）
      if (statusName.includes('预发布') || statusName.includes('发布就绪')) {
        return 90
      }
      // 判断是否测试状态（包含"测试中"、"测试"等关键词）
      if (statusName.includes('测试中') || statusName.includes('测试')) {
        return 70
      }
      // 判断是否开发状态（包含"开发中"、"开发"等关键词）
      if (statusName.includes('开发中') || statusName.includes('开发')) {
        return 30
      }
      // 判断是否规划状态（包含"规划中"、"规划"等关键词）
      if (statusName.includes('规划中') || statusName.includes('规划')) {
        return 10
      }
      // 判断是否草稿状态（包含"草稿"等关键词）
      if (statusName.includes('草稿') || statusName.includes('新建')) {
        return 5
      }
    }
    return 0
  }
  
  // 计算各项的完成率
  const taskProgress = totalTasks.value > 0 ? (completedTasks.value / totalTasks.value) * 100 : 0
  const defectProgress = totalDefects.value > 0 ? (resolvedDefects.value / totalDefects.value) * 100 : 0
  const requirementProgress = totalRequirements.value > 0 ? (completedRequirements.value / totalRequirements.value) * 100 : 0
  const testCaseProgress = totalTestCases.value > 0 ? (passedTestCases.value / totalTestCases.value) * 100 : 0
  
  // 加权平均（任务和需求权重更高）
  const weights = {
    task: totalTasks.value > 0 ? 0.3 : 0,
    defect: totalDefects.value > 0 ? 0.2 : 0,
    requirement: totalRequirements.value > 0 ? 0.3 : 0,
    testCase: totalTestCases.value > 0 ? 0.2 : 0
  }
  
  const totalWeight = weights.task + weights.defect + weights.requirement + weights.testCase
  
  if (totalWeight === 0) {
    return 0
  }
  
  const weightedProgress = (
    taskProgress * weights.task +
    defectProgress * weights.defect +
    requirementProgress * weights.requirement +
    testCaseProgress * weights.testCase
  ) / totalWeight
  
  return Math.round(weightedProgress)
})

const progressStatus = computed(() => {
  const percentage = progressPercentage.value
  const state = getStateByCode(props.version.status)
  const statusName = state?.name || ''
  
  // 判断是否已完成状态（包含"已发布"、"已归档"、"已完成"等关键词）
  if (statusName.includes('已发布') || statusName.includes('已归档') || statusName.includes('已完成')) {
    return 'success'
  }
  
  if (percentage === 100) {
    return 'success'
  }
  
  if (percentage >= 80) {
    return undefined // 默认蓝色
  }
  
  if (percentage >= 50) {
    return 'warning'
  }
  
  return 'exception'
})

const formatProgress = (percentage: number) => {
  const state = getStateByCode(props.version.status)
  const statusName = state?.name || ''
  
  // 如果状态名包含"已发布"或"已归档"，直接返回状态名
  if (statusName.includes('已发布') || statusName.includes('已归档')) {
    return statusName
  }
  
  const totalItems = totalTasks.value + totalDefects.value + totalRequirements.value + totalTestCases.value
  
  if (totalItems > 0) {
    const completedItems = completedTasks.value + resolvedDefects.value + completedRequirements.value + passedTestCases.value
    return `${completedItems}/${totalItems}`
  }
  
  return `${percentage}%`
}
</script>

<style scoped>
.version-progress {
  width: 100%;
}

.progress-bar {
  margin-bottom: 4px;
}

.progress-details {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #666;
  margin-top: 8px;
  flex-wrap: wrap;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.label {
  color: #909399;
  font-weight: 500;
}

.value {
  color: #303133;
  font-weight: 600;
}

.percentage {
  color: #409eff;
  font-size: 11px;
}

/* 不同状态的进度条样式 */
.status-planning :deep(.el-progress-bar__outer) {
  background-color: #f4f4f5;
}

.status-development :deep(.el-progress-bar__inner) {
  background: linear-gradient(to right, #e6a23c, #f7ba2a);
}

.status-testing :deep(.el-progress-bar__inner) {
  background: linear-gradient(to right, #409eff, #66b1ff);
}

.status-pre_release :deep(.el-progress-bar__inner) {
  background: linear-gradient(to right, #e6a23c, #ebb563);
}

.status-released :deep(.el-progress-bar__inner) {
  background: linear-gradient(to right, #67c23a, #85ce61);
}

.status-deprecated :deep(.el-progress-bar__inner) {
  background: linear-gradient(to right, #f56c6c, #f78989);
}

.status-archived :deep(.el-progress-bar__inner) {
  background: linear-gradient(to right, #909399, #a6a9ad);
}
</style>